package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.rmi.dgc.Lease;
import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    @Autowired
    private ApartmentFacilityService apartmentFacilityService;

    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;

    @Autowired
    private ApartmentLabelService apartmentLabelService;

    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private ProvinceInfoService provinceInfoService;

    @Autowired
    private CityInfoService cityInfoService;

    @Autowired
    private DistrictInfoService districtInfoService;

    @Autowired
    private RoomInfoService roomInfoService;

    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;

    @Autowired
    private FacilityInfoMapper facilityInfoMapper;

    @Autowired
    private LabelInfoMapper labelInfoMapper;

    @Autowired
    private FeeValueMapper feeValueMapper;

    @Autowired
    private GraphInfoMapper graphInfoMapper;



    @Override
    public void saveOrUpdateInfo(ApartmentSubmitVo apartmentSubmitVo) {

        boolean isUpdate = apartmentSubmitVo.getId() != null;




        ProvinceInfo province = provinceInfoService.getById(apartmentSubmitVo.getProvinceId());
        apartmentSubmitVo.setProvinceName(province.getName());
        CityInfo city = cityInfoService.getById(apartmentSubmitVo.getCityId());
        apartmentSubmitVo.setCityName(city.getName());
        DistrictInfo district = districtInfoService.getById(apartmentSubmitVo.getDistrictId());
        apartmentSubmitVo.setDistrictName(district.getName());

        saveOrUpdate(apartmentSubmitVo);

        if (isUpdate) {
            //首先要跟新或者删除中间表，来判断一下

            //公寓配套中间表
            LambdaQueryWrapper<ApartmentFacility> FacilitylambdaQueryWrapper = new LambdaQueryWrapper<>();
            FacilitylambdaQueryWrapper.eq(ApartmentFacility::getId,apartmentSubmitVo.getId());
            apartmentFacilityService.remove(FacilitylambdaQueryWrapper);

            //公寓杂费中间信息表
            LambdaQueryWrapper<ApartmentFeeValue> FeelambdaQueryWrapper = new LambdaQueryWrapper<>();
            FeelambdaQueryWrapper.eq(ApartmentFeeValue::getId,apartmentSubmitVo.getId());
            apartmentFeeValueService.remove(FeelambdaQueryWrapper);

            //公寓标签中间表
            LambdaQueryWrapper<ApartmentLabel> LabellambdaQueryWrapper = new LambdaQueryWrapper<>();
            LabellambdaQueryWrapper.eq(ApartmentLabel::getId,apartmentSubmitVo.getId());
            apartmentLabelService.remove(LabellambdaQueryWrapper);


            //删除图片信息
            LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getId,apartmentSubmitVo.getId());
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,apartmentSubmitVo.getId());
            graphInfoService.remove(graphInfoLambdaQueryWrapper);

        }

            //保存公寓配套中间表
           List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
           //从前端传入的对象中获取配套设施的ID列表
           if (!CollectionUtils.isEmpty(facilityInfoIds)){
           //判断传入的设施ID列表是否非空（既不是null也不是空列表）
                List<ApartmentFacility> facilities = new ArrayList<>(facilityInfoIds.size());
                //创建一个List初始容量为施舍ID列表大小
               for (Long facilityInfoId : facilityInfoIds) {
                   //遍历所有ID，寻找对应配套设施
                   ApartmentFacility apartmentFacility = ApartmentFacility.builder().facilityId(facilityInfoId).apartmentId(apartmentSubmitVo.getId()).build();
                   //使用构建者模式创建一个ApartmentFacility对象，并设置其属性
                   //ApartmentFacility.builder()获取对象的构建者模式
                   //.facilityId(facilityInfoId)设置facilityId属性
                   //.apartmentId(apartmentSubmitVo.getId())设置apartmentId属性
                   //.build()创建对象并返回
                   //这段代码处理前端传入的公寓配套设施信息，将这些关联关系批量保存到中间表（ApartmentFacility）中，实现了公寓与配套设施的关联。
                   facilities.add(apartmentFacility);
                   //讲创建的列表添加到列表中
               }
               apartmentFacilityService.saveBatch(facilities);
               //批量保存
           }

           //保存公寓杂费中间表
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
           if (!CollectionUtils.isEmpty(feeValueIds)){
               List<ApartmentFeeValue> feeValues = new ArrayList<>(feeValueIds.size());
               for (Long feeValueId : feeValueIds) {
                   ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder().feeValueId(feeValueId).apartmentId(apartmentSubmitVo.getId()).build();
                   feeValues.add(apartmentFeeValue);
               }
               apartmentFeeValueService.saveBatch(feeValues);
           }

           //保存公寓标签中间表
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
           if (!CollectionUtils.isEmpty(labelIds)){
               List<ApartmentLabel> labels = new ArrayList<>(labelIds.size());
               for (Long labelId : labelIds) {
                   ApartmentLabel apartmentLabel = ApartmentLabel.builder().labelId(labelId).apartmentId(apartmentSubmitVo.getId()).build();
                   labels.add(apartmentLabel);
               }
               apartmentLabelService.saveBatch(labels);
           }

           //保存图片信息
           List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
           if (!CollectionUtils.isEmpty(graphVoList)){
               List<GraphInfo> graphInfos = new ArrayList<>(graphVoList.size());
               for (GraphVo graphVo : graphVoList) {
                   GraphInfo graphInfo = new GraphInfo();
                   graphInfo.setName(graphVo.getName());
                   graphInfo.setUrl(graphVo.getUrl());
                   graphInfo.setItemId(apartmentSubmitVo.getId());
                   graphInfo.setItemType(ItemType.APARTMENT);
                   graphInfos.add(graphInfo);
               }
               graphInfoService.saveBatch(graphInfos);
           }

        }

    @Override
    public void FindPage(IPage<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        apartmentInfoMapper.FindPage(page,queryVo);
    }

    @Override
    public ApartmentDetailVo getDetailById(Long id) {

        //查询id对应的公寓详情
        ApartmentInfo apartmentInfo = getById(id);

        //查询公寓对应配套
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.getDetailById(id);

        //查询公寓对应标签
        List<LabelInfo> labelInfoList = labelInfoMapper.getDetailById(id);

        //查询公寓对应图片
        List<GraphVo> graphVoList = graphInfoMapper.getDetailById(ItemType.APARTMENT,id);

        //查询公寓对应杂费
        List<FeeValueVo> feeValueVoList = feeValueMapper.getDetailById(id);



        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setGraphVoList(graphVoList);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);
        apartmentDetailVo.setLabelInfoList(labelInfoList);

        BeanUtils.copyProperties(apartmentInfo,apartmentDetailVo);

        return apartmentDetailVo;
    }

    @Override
    public void removeById(Long id) {
        LambdaQueryWrapper<RoomInfo> roomInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomInfoLambdaQueryWrapper.eq(RoomInfo::getApartmentId,id);
        Long count = roomInfoService.count(roomInfoLambdaQueryWrapper);
        if (count>0){
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }
        removeById(id);
        //删除图片信息
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,id);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType,ItemType.APARTMENT);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);

        //删除配套
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,id);
        apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);

        //删除标签
        LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,id);
        apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);

        //删除杂费
        LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,id);
        apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
    }


}





